/**
 * HomeController
 *
 * @description :: Server-side logic for managing homes
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */
var moment = require('moment');
// var request = require('request');
var crypto = require('crypto');
var omipay = require('./OmiPay');
var token = require('./token');
const apiUrl = 'http://localhost:8333/api/';
const apiLib = require('./MainApi');
const Promise = require('promise');
var co = require('co')
var request = require('co-request');
const wms = require('./WmsApi');
const appId = 'wxbc675391baa7ae28';
const appSecret = 'c9dc72fc2d2162fb7f8e65b97f1c3d5a';
const royal = require('./RoyalPay');
const wechat = require('./wechat');

function de_duplication(arr) {
  var de_array = [];
  for (var i=0; i<arr.length; i++) {
    if (de_array.indexOf(arr[i]) == -1) {
      de_array.push(arr[i]);
    }
  }
  return de_array;
}

module.exports = {
  index: function (req, res) {
    if(typeof(req.param('code')) != 'undefined'){
      wechat.get_token_by_code(req.param('code'), function (call) {
        console.log('token is:', call);
        var access_token = call.access_token;
        var openid = call.openid;
        wechat.get_info_by_token(access_token, openid, function (callback) {
          console.log('user info is:', callback);
          var openid = callback.openid;
          wms.get_customer_by_openid(openid, function (call) {
            if (call.length == 0) {
              res.view('bind_phone', {user_info: callback, });
            } else {
              console.log('user info is:', call);
              res.view('index', {user_info: call[0], wechat_info: callback});
            }
          })
        })
      })
    } else {
      res.view('index');
    }
    // var echostr = req.param('signature');
    // console.log(echostr);
    // console.log('user_info index:',req.session.user_info);
    // var Promise = require('promise');
    // res.view('index', {user_info: req.session.user_info});
    // if (!req.session.user_info) {
    //   var code = req.param('code');
    //   console.log('code:',code);
    //   var token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='+appId+'&secret='+appSecret+'&code='+code+'&grant_type=authorization_code';
    //   request(token_url, function (err, resp, body) {
    //     if (err) return res.serverError(err);
    //     var access_token = JSON.parse(body).access_token;
    //     var openid = JSON.parse(body).openid;
    //     var user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='+access_token+'&openid='+openid+'&lang=zh_CN';
    //     request(user_info_url, function (err, resp, body) {
    //       if (err) return res.serverError(err);
    //       var user_info = JSON.parse(body);
    //       console.log('user info is:', user_info);
    //       req.session.user_info = user_info;
    //       var user_info = {
    //         openid: user_info.openid,
    //         avatar: user_info.headimgurl,
    //         username: user_info.nickname
    //       }
    //       // User.find({openid: openid}).then(function (result) {
    //       //   if (result.length == 0) {
    //       //     User.create(user_info).then(function (created) {
    //       //       console.log('create new user:', created);
    //       //     })
    //       //   } else {
    //       //     console.log('already registered');
    //       //   }
    //       // })
    //       res.view('index', {user_info: req.session.user_info});
    //     })
    //   })
    // } else {
    //   res.view('index', {user_info: req.session.user_info});
    // }
  },

  list: function (req, res) {
    res.view('listNew');
  },

  login: function (req, res) {
    res.view('login');
  },

  account: function (req, res) {
    res.view('account');
  },

  detail: function (req, res) {
    res.view('detail');
  },

  access: function (req, res) {
    request('http://www.baidu.com', function (error, response, body) {
      console.log('error:', error); // Print the error if one occurred
      console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
      console.log('body:', body); // Print the HTML for the Google homepage.
      res.send(response);
    });
  },

  msg: function (req, res) {
    request.post('https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=mP06jN6kJERWFnHonPUbbV6wAbRBsrFf1ekROTT7Y7BEIITTaR1B24xINciIn3N6', {form: {
      "touser": "steph",
      "msgtype": "text",
      "agentid": 11,
      "text": {
        "content": "Holiday Request For Pony(http://xxxxx)"
      },
      "safe":0
    }}, function (err, response, body) {
      console.log(body);
      res.send(response);
    })
  },

  search: function (req, res) {
    var q = req.param('q');
    res.view('searchResult',{q: q});

    // var catId = req.body.catId;
    // if (catId > 0 ) {
    //   List.find({id: catId}).then(function (result) {
    //     Product.find({category: result[0].name, name: {contains: q}}).then(function (record) {
    //       if (record.length == 0) {
    //         Product.find({category: result[0].name, pinyin: {contains: q}}).then(function (raw) {
    //           res.send(raw);
    //         }).catch(function (err) {
    //           res.serverError(err);
    //         })
    //       }
    //       res.send(record);
    //     }).catch(function (err) {
    //       res.serverError(err);
    //     }).catch(function (err) {
    //       res.serverError(err);
    //     })
    //   })
    // } else {
    //   Product.find({name: {contains: q}}).then(function (record) {
    //     res.send(record);
    //   }).catch(function (err) {
    //     res.serverError(err);
    //   })
    // }
    // var q = req.params.q;
    // var cat = req.params.cat;
    // Cate
    // Product.find({name: {contains: q}}).then(function (record) {
    //   res.send(record);
    // }).catch(function (err) {
    //   res.serverError(err);
    // })
  },

  getTags: function (req, res) {
    var catId = req.params.catId;
    if (catId == 'all') {
      Product.query('SELECT brand FROM t_inv_inventory GROUP BY brand', function (err, rawResult) {
        if (err) return res.serverError(err);
        console.log(rawResult);
        res.json(rawResult);
      })
    } else {
      List.find({id: catId}).then(function (record) {
        Product.query('SELECT brand FROM t_inv_inventory WHERE category = ? GROUP BY brand', [record[0].name], function (err, rawResult) {
          if (err) return res.serverError(err);
          console.log(rawResult);
          res.json(rawResult);
        })
      }).catch(function (err) {
        res.serverError(err);
      })
    }
  },

  getFeatured: function (req, res) {
    FeaturedBrand.find().then(function (record) {
      res.send(record);
    }).catch(function (err) {
      res.serverError(err);
    })
  },

  getProductsByBrand: function (req, res) {
    var brandName = req.params.brandName;
    var catId = req.params.catId;
    if ( brandName == 'all' && catId == 'all') {
      Product.find().then(function (record) {
        res.send(record);
      })
    } else {
      if (brandName == 'all' && catId != 'all') {
        List.find({id: catId}).then(function (record) {
          Product.find({category: record[0].name}).then(function (result) {
            res.send(result)
          })
        })
      } else {
        if (brandName != 'all' && catId == 'all') {
          Product.find({brand: brandName}).then(function (record) {
            res.send(record);
          })
        } else {
          List.find({id: catId}).then(function (record) {
            Product.find({brand: brandName, category: record[0].name}).then(function (result) {
              res.send(result);
            })
          })
        }
      }
    }
    // Product.find({brand: brandName}).then(function (record) {
    //   console.log(record);
    //   res.send(record);
    // }).catch(function (err) {
    //   res.serverError(err);
    // })
  },

  // getBrandByCat: function (req, res) {
  //   List.find({id: req.params.id}).then(function (record) {
  //     var category = record[0].name;
  //     Product.find({category: category}).then(function (result) {
  //       console.log('get brands');
  //       var brandArr = [];
  //       for (var i=0; i<result.length; i++) {
  //         brandArr.push(result[i].brand)
  //       }
  //     })
  //   })
  // },

  getRate: function (req, res) {
    omipay.getExRate(function (callback) {
      res.send(callback);
    })
    // var m_number = 'M00178';
    // var timestamp = moment().format('x');
    // var nonce_str = 'ngqit93n4go';
    // var secret_key = 'Sm5617';
    // var encStr = m_number + '&' + timestamp + '&' + nonce_str + '&' + secret_key;
    // var md5 = crypto.createHash('md5');
    // md5.update(encStr);
    // var result = md5.digest('hex').toUpperCase();
    // var uri = 'https://www.omipay.com.au/omipay/api/v1/GetExchangeRate?m_number=' + m_number + '&timestamp=' + timestamp + '&nonce_str=' + nonce_str + '&sign=' + result;
    // console.log(uri);
    // request({
    //   url: uri,
    //   method: 'POST',
    //   json: true,
    //   headers: {
    //     "content-type": "application/json",
    //   },
    //   body: {}
    // }, function (err, resp, body) {
    //   if (!err) {
    //     console.log(body);
    //     res.send(body);
    //   }
    // })
  },

  getApiToken: function (req, res) {
    return token.getApiToken();
  },

  //商品相关接口

  //搜索商品
  searchProduct: function (req, res) {
    var keyword = req.param('q');
    var category = req.param('cat');
    var criteriaList = ['brand', 'pinyin', 'name', 'brief_name'];
    var searchResult = [];

    // async.eachSeries(criteriaList,function(item,callback){
    //   var criteria = encodeURI(item +'=lk,%'+keyword+'%');
    //   apiLib.search(criteria, function (call) {
    //     console.log('search result:',call);
    //     searchResult.push(call);
    //   });
    //   console.log("searchRRRRRRR:"+searchResult);
    //   callback(null);
    // },function(err){
    //   console.log("eachSeries:"+searchResult);
    //   res.ok();
    // });

    co(function *(){
      for(var i =0; i<criteriaList.length;i++) {
        if (category) {
          console.log(category);
          var criteria = encodeURI(criteriaList[i] + '=lk,%' + keyword + '%&category=lk,%' + category);
        } else {
          var criteria = encodeURI(criteriaList[i]+'=lk,%'+keyword+'%');
        }
        var result = JSON.parse((yield *apiLib.search(criteria))|| "[]");

        result.forEach(function(x){
          if(!searchResult.some(function(r){
            return r.id == x.id
          })){
            searchResult.push(x)
          }
        })
      }
      console.log('these are searchresults', searchResult);
      res.send(searchResult)
    }).catch(function(err) {
      res.serverError(err)
    })
    // for(var i =0; i<criteriaList.length;) {
    //   var criteria = encodeURI(criteriaList[i]+'=lk,%'+keyword+'%');
    //   console.log('search criteria:',criteria);
    //   apiLib.search(criteria, function (call) {
    //     console.log('search result:',call);
    //     searchResult.push(call);
    //   });
    //   i++;
    //   if (i == criteriaList.length) {
    //     res.send(searchResult);
    //   }
    // };
  },
  // preOrder: function (req, res) {
  //   var order = JSON.stringify(req.body.order);
  //   var order_specs = JSON.stringify([req.body.order_specs]);
  //   console.log('order:',order,order_specs);
  //   token.getApiToken(function (result) {
  //     var reqBody = {
  //       order: order,
  //       order_specs: order_specs,
  //       order_shp_boxes: [],
  //     };
  //     request({
  //       url: apiUrl+'sales/',
  //       method: 'POST',
  //       headers: {
  //         'Content-Type': 'application/json',
  //         Authorization: result,
  //       },
  //       form: reqBody,
  //     }, function (err, result) {
  //       if (err) res.serverError(err);
  //       res.send(result);
  //     })
  //   })
  // },
  //
  // createOrder: function (req, res) {
  //   var order = JSON.stringify(req.body.order);
  //   var order_specs = JSON.stringify(req.body.order_specs);
  //   var box_no = JSON.stringify(req.body.box_no);
  //   var reqBody = {
  //
  //   }
  // }
  getAllProducts: function (req, res) {
    apiLib.getAllProducts(function (call) {

    })
  },

  testOrderApi: function (req, res) {
    var json = req.body.orderInfo;
    wms.preOrder(json, function(call){
      res.send(call);
    })
  },

  testBoxInfo: function (req, res) {
    var id = req.param('id');
    wms.getBoxNo(id, function (call) {
      res.send(call);
    })
  },

  getBrandsByCat: function (req, res) {
    var cat = req.param('cat');
    apiLib.getBrandsByCat(cat, function (call) {
      res.send(call);
    })
  },

  getAllCats: function (req, res) {
    apiLib.getAllCats(function (call) {
      res.send(call);
    })
  },

  getAllBrands: function (req, res) {
    apiLib.getAllBrands(function (call) {
      res.send(call);
    })
  },

  productList: function (req, res) {
    var catName = req.params.catName;
    apiLib.get_pagination(catName, 0, function (call) {
      var products = JSON.parse(call);
      Classify.find().then(function (records) {
        var keywords = [];
        for(var i=0; i<records.length; i++) {
          var sn_array = JSON.parse(records[i].child_sn);
          var p_info = JSON.parse(records[i].parent_info);
          for(var j=0; j<products.length; j++){
            if(sn_array.indexOf(products[j].sn) != -1){
              products.splice(j, 1, p_info);
            }
          }
        }
        console.log('duplicate products:', products);
        var products_classified = de_duplication(products);
        console.log('de_duplicated products:',products_classified);
        royal.get_current_ex(function (rate) {
          console.log('current rate:',rate);
          res.view('product_list', {data: products_classified, cat: catName, rate: rate});
        })
      })
    })
  },

  getProductsPagination: function (req, res) {
    var catName = req.params.cat_id;
    var offset = req.param('offset');
    console.log('offset is:', offset);
    apiLib.get_pagination(catName, offset, function (call) {
      var products = JSON.parse(call);
      if (products.length == 0) {
        res.send([]);
      } else {
        console.log('products:',products)
        Classify.find().then(function (records) {
          var keywords = [];
          for(var i=0; i<records.length; i++) {
            var sn_array = JSON.parse(records[i].child_sn);
            var p_info = JSON.parse(records[i].parent_info);
            for(var j=0; j<products.length; j++){
              if(sn_array.indexOf(products[j].sn) != -1){
                products.splice(j, 1, p_info);
              }
            }
          }
          console.log('duplicate products:', products);
          var products_classified = de_duplication(products);
          console.log('de_duplicated products:',products_classified);
          res.send(products_classified);
        })
      }
    })
  },

  productDetail: function (req, res) {
    var sn = req.params.sn;
    console.log(sn);
    apiLib.getProductBySn(sn, function (call) {
      var product = JSON.parse(call);
      console.log(product);
      royal.get_current_ex(function (rate) {
        res.view('product_detail', {data: product, rate: rate});
      })
    })
  },

  productHot: function (req, res) {
    res.view('product_hot');
  },

  productSpecial: function (req, res) {
    res.view('product_special');
  },

  productNew: function (req, res) {
    res.view('product_new');
  },

  freeShipping: function (req, res) {
    res.view('product_free_shipping');
  },

  featuredProducts: function (req, res) {
    var feature = req.param('feature');
    Feature.find({feature: feature}).then(function (record) {
      if (record.length == 0) {
        res.send([]);
      } else {
        var p_sn_list = JSON.parse(record[0].product);
        var get_products_info = new Promise(function (resolve, reject) {
          var p_info = [];
          for (var i=0; i<p_sn_list.length; i++) {
            apiLib.getProductBySn(p_sn_list[i], function (call) {
              p_info.push(JSON.parse(call)[0]);
              if (p_info.length == p_sn_list.length) {
                resolve(p_info);
              }
            })
          }
        });
        Promise.all([get_products_info]).then(function (result) {
          var p_list = result[0];
          res.send(p_list);
        })
      }
    })
  },
}


